//
//  SimilarAdsCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/21/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class SimilarAdsCell: UITableViewCell, MainVCCell {
    
    // MARK: - Outlets

    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 21, weight: .regular)
        lbl.textColor = .white
        lbl.sizeToFit()
        lbl.numberOfLines = 0
        lbl.text = "Похожие объявления"
        return lbl
    }()
    
    private lazy var postsScrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        return scrollView
    }()
    
    private lazy var postsStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.alignment = .leading
        stack.distribution = .fillEqually
        stack.spacing = 12
        return stack
    }()
    
    // MARK: - Props
    
    var delegate: MainVCCellActionsDelegate!
    private var posts: [PostModel] = []
    
    // MARK: - Actions
    
    @objc private func postTapped (sender: GestureWithTag) {
        delegate.openAdvert(advert: posts[sender.tag].post)
    }
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: - Configure Cells

extension SimilarAdsCell: ConfigurableCell {
    
    func configure(data object: [PostModel]?, index: Int) {
        self.posts = object ?? []
        self.addItems(posts: self.posts)
    }

    func returnData() -> [PostModel]? {
        return nil
    }
}



extension SimilarAdsCell {
    
    private func addViews () {
        self.contentView.addSubview(titleLbl)
        self.contentView.addSubview(postsScrollView)
        postsScrollView.addSubview(postsStack)
        
        self.contentView.backgroundColor = .darkBlueColor
        
        titleLbl.snp.makeConstraints { (make) in
            make.leading.trailing.top.equalToSuperview().inset(16)
            make.height.equalTo(32)
        }
        
        postsScrollView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLbl.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(226)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        postsStack.snp.makeConstraints { (make) in
            make.top.bottom.leading.equalToSuperview()
        }
    }
    
    private func addItems (posts: [PostModel]) {
        
        let postsWidth = posts.count * 150 + (posts.count - 1) * 12
        
        _ = postsStack.arrangedSubviews.map {
            postsStack.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        
        for (i, post) in posts.enumerated() {
            let text = [post.marka, post.model, post.pokolenie, post.serie, post.modification].joined(separator: " ")
            let postView = AdItemView(imageURL: post.images.first?.image, price: post.price, description: text)
            
            let tap = GestureWithTag(target: self, action: #selector(postTapped(sender:)))
            tap.tag = i
            postView.addGestureRecognizer(tap)
            
            self.postsStack.addArrangedSubview(postView)
        }
        postsScrollView.contentSize = CGSize(width: postsWidth, height: 226)
    }
}




final class AdItemView: UIView  {
    
    private lazy var wallpaperImgView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 7
        return imageView
    }()
    
    private lazy var priceLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 18, weight: .regular)
        lbl.numberOfLines = 1
        lbl.sizeToFit()
        lbl.textColor = .white
        return lbl
    }()
    
    private lazy var descriptionLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 15, weight: .bold)
        lbl.textColor = .greyBlue
        lbl.sizeToFit()
        lbl.numberOfLines = 5
        return lbl
    }()
    
    init (imageURL: String?, price: String, description: String) {
        super.init(frame: .zero)
        self.addViews(imageURL: imageURL, price: price, description: description)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addViews (imageURL: String?, price: String, description: String) {
        addSubview(wallpaperImgView)
        addSubview(priceLbl)
        addSubview(descriptionLbl)
        
        snp.makeConstraints { (make) in
            make.width.equalTo(150)
        }
        
        wallpaperImgView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(84)
        }
        
        priceLbl.snp.makeConstraints { (make) in
            make.top.equalTo(wallpaperImgView.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(30)
        }
        
        descriptionLbl.snp.makeConstraints { (make) in
            make.top.equalTo(priceLbl.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        self.setUpUI(imageURL: imageURL, price: price, description: description)
    }
    
    private func setUpUI(imageURL: String?, price: String, description: String) {
        if let urlString = imageURL {
            wallpaperImgView.sd_setImage(with: URL(string: urlString), placeholderImage: UIImage(named: "noPhoto"))
        } else {
            wallpaperImgView.image = UIImage(named: "noPhoto")
        }
        priceLbl.text = price
        descriptionLbl.text = description
    }
}
